﻿using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Forms;

namespace TurtleEngine
{
	 /// <summary>
	 ///
	 /// </summary>
	 public partial class SQLDoc : Form
	 {
		  /// <summary>
		  /// The object by types to write
		  /// </summary>
		  private static readonly List<string> objectByTypesToWrite =
			  new List<string>(new[] { "Tables", "Views", "Procedures", "Functions", "Triggers", "UserDefinedDataTypes" });

		  /// <summary>
		  /// The server info to write
		  /// </summary>
		  private static readonly List<string> serverInfoToWrite =
			 new List<string>(new[]
								{
									"InstanceInformation", "DataSourceInformation", "DataTypes", "Restrictions", "ReservedWords", "Users",
									"Databases"
								});

		  /// <summary>
		  /// The db connection
		  /// </summary>
		  private static SqlConnection dbConnection;

		  /// <summary>
		  /// The entire database
		  /// </summary>
		  private static DataSet entireDatabase = new DataSet("EntireDatabase");

		  /// <summary>
		  /// Initializes a new instance of the <see cref="SQLDoc" /> class.
		  /// </summary>
		  public SQLDoc()
		  {
				InitializeComponent();

				//SqlClientMetaDataCollectionNames
				//randomTry();
				//GetMetaDataCollections();

				//Utility.OpenConnection();

				//SMOHelper.TriggersHelper.GetTriggers("AdventureWorks");
				//SMOHelper.UserDefinedDataTypesHelper.GetUserDefinedDataTypes("AdventureWorks");
				//InstanceInformationHelper.GetInstanceInformation();
				//DataSourceInformationHelper.GetDataSourceInformation();
				//DataTypesHelper.GetDataTypes();
				//RestrictionsHelper.GetRestrictions();
				//ReservedWordsHelper.GetReservedWords();
				//UsersHelper.GetUsers();
				//DatabasesHelper.GetDatabases();
				//ColumnsHelper.GetColumns();
				//ForeignKeysHelper.GetForeignKeys();
				//IndexColumnsHelper.GetIndexColumns();
				//IndexesHelper.GetIndexes();
				//TablesHelper.GetTables();
				//ViewColumnsHelper.GetViewColumns();
				//ViewsHelper.GetViews();
				//ProcedureParametersHelper.GetProcedureParameters();
				//ProceduresHelper.GetProcedures();
				//UserDefinedTypesHelper.GetUserDefinedTypes();

				////AllColumnsHelper.GetAllColumns();
				////ColumnSetColumnsHelper.GetColumnSetColumns();
				////StructuredTypeMembersHelper.GetStructuredTypeMembers();
				////JoinAllDataTables();
				////JoinColumnsWithTables();

				//Utility.CloseConnection();

				//WriteCHMHelp();
		  }

		  /// <summary>
		  /// Gets the DB connection.
		  /// </summary>
		  /// <value>
		  /// The DB connection.
		  /// </value>
		  public static SqlConnection DBConnection
		  {
				get { return dbConnection; }
		  }

		  /// <summary>
		  /// Gets the object by types to write.
		  /// </summary>
		  /// <value>
		  /// The object by types to write.
		  /// </value>
		  public static List<string> ObjectByTypesToWrite
		  {
				get { return objectByTypesToWrite; }
		  }

		  /// <summary>
		  /// Gets the server info to write.
		  /// </summary>
		  /// <value>
		  /// The server info to write.
		  /// </value>
		  public static List<string> ServerInfoToWrite
		  {
				get { return serverInfoToWrite; }
		  }

		  /// <summary>
		  /// Compiles the CHM help.
		  /// </summary>
		  private void CompileCHMHelp()
		  {
				string location = Assembly.GetExecutingAssembly().Location;
				location = location.Substring(0, location.LastIndexOf("\\"));

				var startInfo = new ProcessStartInfo();
				startInfo.CreateNoWindow = true; // false;
				startInfo.FileName = @"C:\Program Files\HTML Help Workshop\hhc.exe";
				startInfo.WindowStyle = ProcessWindowStyle.Hidden; // ProcessWindowStyle.Normal;
				startInfo.Arguments = location + "\\AdventureWorks.hhp";

				try
				{
					 using (Process exeProcess = Process.Start(startInfo))
					 {
						  exeProcess.WaitForExit();
					 }
				}
				catch (Exception ex)
				{
					 MessageBox.Show(ex.Message);
				}
		  }

		  /// <summary>
		  /// Gets the meta data collections.
		  /// </summary>
		  private void GetMetaDataCollections()
		  {
				DataTable dt = Utility.DBConnection.GetSchema("MetaDataCollections");

				//Utility.PrintDatatable(dt);
		  }

		  /// <summary>
		  /// Joins all data tables.
		  /// </summary>
		  private void JoinAllDataTables()
		  {
				//entireDatabase.Tables.Add(instanceInformation);
				//entireDatabase.Tables.Add(dataSourceInformation);
				//entireDatabase.Tables.Add(dataTypes);
				//entireDatabase.Tables.Add(restrictions);
				//entireDatabase.Tables.Add(reservedWords);
				//entireDatabase.Tables.Add(users);
				//entireDatabase.Tables.Add(databases);

				//entireDatabase.Tables.Add(tables);
				//entireDatabase.Tables.Add(columns);
				//entireDatabase.Tables.Add(allColumns);
				//entireDatabase.Tables.Add(columnSetColumns);
				//entireDatabase.Tables.Add(structuredTypeMembers);
				//entireDatabase.Tables.Add(views);
				//entireDatabase.Tables.Add(viewColumns);
				//entireDatabase.Tables.Add(procedureParameters);
				//entireDatabase.Tables.Add(procedures);
				//entireDatabase.Tables.Add(foreignKeys);
				//entireDatabase.Tables.Add(indexColumns);
				//entireDatabase.Tables.Add(indexes);
				//entireDatabase.Tables.Add(userDefinedTypes);

				//File.WriteAllText(@"xml\entireDB.xml", entireDatabase.GetXml());
		  }

		  /// <summary>
		  /// Joins the columns with tables.
		  /// </summary>
		  private void JoinColumnsWithTables()
		  {
				//foreach (DataRow row in TablesHelper.Tables.Rows)
				//{
				//    string table_Schema = row["TABLE_SCHEMA"].ToString();
				//    string table_Name = row["TABLE_NAME"].ToString();

				//    DataView dv = new DataView(ColumnsHelper.Columns);
				//    dv.RowFilter = "TABLE_SCHEMA = '" + table_Schema + "' AND TABLE_NAME = '" + table_Name + "'";

				//    string xmlfile = table_Schema + "." + table_Name;
				//    string xslFile = ColumnsHelper.Columns.TableName;
				//    string htmlFile = xmlfile;

				//    Utility.WriteDatatable(dv.ToTable(), xmlfile, xslFile, htmlFile);
				//}
		  }

		  /// <summary>
		  /// Randoms the try.
		  /// </summary>
		  private void randomTry()
		  {
				var serverConnection = new ServerConnection(Utility.DBConnection);
				var server = new Server(serverConnection);

				Database northwind = server.Databases["AdventureWorks"];
				Table categories = northwind.Tables["AWBuildVersion"];
				StringCollection script = categories.Script();
				var scriptArray = new string[script.Count];

				script.CopyTo(scriptArray, 0);
		  }

		  /// <summary>
		  /// Writes the CHM help.
		  /// </summary>
		  private void WriteCHMHelp()
		  {
				//HHCWriter hhc = new HHCWriter();
				//hhc.TOCFileName = "Table of Contents.hhc";
				//hhc.Write();

				//CompileCHMHelp();
		  }
	 }
}